package pers.archives.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import pers.archives.common.utils.redis.RedisObjectSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.nio.charset.Charset;

/* REDIS 配置类
 *@program:archives-parent
 *@author: 赵浩浩
 *@Time: 2020/9/7  14:22
 */
@Slf4j
@Configuration
@PropertySource("classpath:/redis.properties")
public class RedisConfig {

    @Value("${redis.host}")
    private String host;

    @Value("${redis.port}")
    private int port;

    @Value("${redis.password}")
    private String password;

    @Value("${redis.database}")
    private int database;

    @Value("${redis.timeout}")
    private int timeout;

    @Value("${redis.pool.max-active}")
    private int maxActive;

    @Value("${redis.pool.max-idle}")
    private int maxIdle;

    @Value("${redis.pool.min-idle}")
    private int minIdle;

    @Value("${redis.pool.max-wait}")
    private long maxWait;

    @Bean
    public RedisConnectionFactory jedisConnectionFactory() {
        log.info("开始加载Redis链接池......");
        long start = System.currentTimeMillis();
        JedisConnectionFactory factory = new JedisConnectionFactory();
        try {
            factory.setHostName(host);
            factory.setPort(port);
            factory.setPassword(password);
            factory.setDatabase(database);
            factory.setTimeout(timeout);
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(maxActive);
            jedisPoolConfig.setMaxIdle(maxIdle);
            jedisPoolConfig.setMinIdle(minIdle);
            jedisPoolConfig.setMaxWaitMillis(maxWait);
            factory.setPoolConfig(jedisPoolConfig);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Redis链接池加载失败......");
        }
        log.info("Redis链接池加载成功、耗时:[{}] 毫秒 ......",System.currentTimeMillis() - start);
        return factory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }
}
